package com.lihan.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;


/**
 * ClassName: ChatHandler
 * Package: com.lihan.websocket
 * Description:
 *  心跳机制
 * @Author 李涵
 * @Create 2025-02-27 20:10
 * @Version 1.0
 */
/*
* 用于检测channel 的心跳handler
* 重写父类的方法，ChannelInboundHandlerAdapter
* */
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if(evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent) evt;
            if(event.state() == IdleState.READER_IDLE){
                System.out.println("进入读空闲");
            }else if(event.state() == IdleState.WRITER_IDLE){
                System.out.println("进入写空闲");
            }else if(event.state() == IdleState.ALL_IDLE){
                System.out.println("channel 关闭之前 users的数量："+ ChatHandler.users.size());
                Channel channel = ctx.channel();
                //资源释放channel
                channel.close();
                System.out.println("channel 关闭之后 users的数量："+ ChatHandler.users.size());
            }
        }

    }
}
